/************************************************************
 * Copyright (C), 2022-2030, dina. Co., Ltd.
 * FileName:        serialport_plugin.h
 * Author:          Dan Yin
 * Date:            022-11-22
 * Description:     the class of serialport plugin
 * Version:         1.0.0.0
 **********************************************************/

#ifndef SERIALPORT_PLUGIN_H
#define SERIALPORT_PLUGIN_H

#include "i_serialport.h"
#include "def_serialport.h"

class SerialportPlugin : public ISerialport
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID ISerialport_iid FILE "serialport.json")
    Q_INTERFACES(ISerialport)

public:
    // default constructor
    explicit SerialportPlugin(QObject *parent = nullptr);

    // open a serial port
    virtual int openSerialport() Q_DECL_OVERRIDE;

    // close a serial port
    virtual void closeSerialport() Q_DECL_OVERRIDE;

    // send an command package
    virtual int sendCommand(const QByteArray baInput, bool bQueued) Q_DECL_OVERRIDE;

    // send an command & receive data
    virtual int execCommand(QByteArray &baDataInOut, const int nSleep) Q_DECL_OVERRIDE;

signals:
    // the signal that fetch a payload packet from serialport
    void signalPayloadFetched(const QByteArray &baData);

    // the signal that build & send an ack command
    void signalBuildACK(const ST_MIN_PKG_INFO &stPkgInfo);

    // the signal that replay an ack comand to COM
    void signalReplyACK(QByteArray baPacket, bool bQueued);

private slots:
    // received data from COM
    void slotDataReceived(const QByteArray &baData);

    // build & send an ACK command
    void slotBuildACK(const ST_MIN_PKG_INFO &stPkgInfo);

private:
    // parse the received package
    int _parseRcvPkg(const QByteArray &baPkgInfo, bool bFetchData);

private:
    QObject *m_pParent;

    // Fetch data or not
    bool m_bFetchData = false;
};

#endif // SERIALPORT_PLUGIN_H
